package com.qzl.server.handler;

import cn.hutool.json.JSONUtil;
import com.qzl.common.netty.config.ChatConfig;
import com.qzl.common.netty.message.Message;
import com.qzl.common.netty.utis.ChatUtils;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

/**
 * @author: qzl
 * @date : 2025/6/24 14:16
 * @description: websocket消息转Message消息
 */
public class WebSocketToMessageHandler  extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof TextWebSocketFrame) {
            String text = ((TextWebSocketFrame) msg).text();
            Message message = JSONUtil.toBean(text, Message.class); // 转换为统一对象
            message.setSequenceId(ChatUtils.getSequenceId());
            ctx.fireChannelRead(message); // 向后传播
        } else if (msg instanceof BinaryWebSocketFrame) { //  二进制消息
            ByteBuf buf = ((BinaryWebSocketFrame) msg).content();
            byte[] data = new byte[buf.readableBytes()];
            buf.readBytes(data);
            Message message = new Message(); // 可按需改为二进制解析
            message.setData(data);
            message.setMessageType((int) ChatConfig.WEBSOCKET_FILE);
            message.setSequenceId(ChatUtils.getSequenceId());
            ctx.fireChannelRead(message);
        } else {
            // 其他类型的 frame 直接透传
            ctx.fireChannelRead(msg);
        }
    }
}
